
/**
*网络聊天工具

*左下角输入框输入对方的ip地址
*右下角输入框输入要发送的消息
*端口号：3000
*接收的消息在上方对话框中显示，新消息在上面
*/


import java.awt.*;
import java.awt.event.*;
import java.net.*;

class Chat extends Frame
{
 List lst = new List(8);     //最多显示六条
 TextField tfIP = new TextField(13);  //IP地址输入文本框
 TextField tfData = new TextField(50); //定义输入消息文本框
 DatagramSocket ds = null;

 public Chat() {
  try
  {
   ds = new DatagramSocket(3000);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  this.add(lst,"Center");  //增加列表框
  Panel p = new Panel();
  this.add(p,"South");

  p.setLayout(new BorderLayout());
  p.add(tfIP,"West");   //IP输入
  p.add(tfData,"East");  //消息输入

  new Thread(new Runnable()
  {
   public void run()
   {
    byte buf [] =new byte[1024];
    DatagramPacket dp = new DatagramPacket(buf,1024);
    //显示消息
    while(true)
    {
     try
     {
      ds.receive(dp);
      lst.add(new String(buf,0,dp.getLength())+
      "    -->IP："+dp.getAddress().getHostAddress()+" Port:"+dp.getPort(),0);
     //新消息指定显示在第一行
     //显示格式：消息from ip地址：端口号
     }
     catch (Exception e)
     {
      if(!ds.isClosed())
      {
       e.printStackTrace();
      }
     }
    }
   }
  }).start();

  tfData.addActionListener(new ActionListener()
  {
   public void actionPerformed(ActionEvent e)
   {
    //取出消息及ip文本框中的内容
    byte [] buf;
    buf =tfData.getText().getBytes();
    try
    {
     DatagramPacket dp = new DatagramPacket(buf,buf.length,
      InetAddress.getByName(tfIP.getText()),3000);
     ds.send(dp);
    }
    catch (Exception ex)
    {
     ex.printStackTrace();
    }
    //清空
    tfData.setText("");
   }
  });
  addWindowListener(new WindowAdapter()
  {
   public void windowClosing(WindowEvent e)
   {
    ds.close();
    dispose();
    System.exit(0);
   }
  });
 }

 public static void main(String args[])
 {
  System.out.println("Starting Chat……");
  Chat mainFrame = new Chat();
  mainFrame.setSize(500,500);
  mainFrame.setTitle("迷你聊天工具");
  mainFrame.setVisible(true);
  mainFrame.setResizable(false);
 }
}